﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using Pikapika.Models.ViewModels.Home;

namespace Pikapika.Models
{
    public static class NovelQueryExtensions
    {

        public static ObjectQuery<Novel> IncludeNovelChapters(this ObjectQuery<Novel> query)
        {
            return query.Include("NovelVolumes.NovelChapters");
        }

        public static ObjectQuery<Novel> IncludeAnnotations(this ObjectQuery<Novel> query)
        {
            return query.Include("NovelVolumes.NovelChapters.Annotations");
        }

        public static IEnumerable<NovelChapter> GetSortedChapters(this NovelVolume volume)
        {
            if (volume == null)
                throw new ArgumentNullException("volume", "volume is null.");

            return (from c in volume.NovelChapters
                    orderby c.SortIndex ascending, c.Id ascending
                    select c);
        }
        public static IEnumerable<NovelVolume> GetSortedVolumes(this Novel novel)
        {
            if (novel == null)
                throw new ArgumentNullException("novel", "novel is null.");

            return (from n in novel.NovelVolumes
                    orderby n.SortIndex ascending, n.Id ascending
                    select n);
        }

        public static List<IndexLatestNovel> GetLatestNovels(this PikapikaDBEntities ctx)
        {
            return GetLatestNovels(ctx, Properties.Settings.Default.HomeLatestNovelDisplayCount);
        }
        public static List<IndexLatestNovel> GetLatestNovels(this PikapikaDBEntities ctx, int maxItems)
        {
            return (from ch in ctx.NovelChapters
                    group ch by ch.NovelVolume.NovelId into g
                    let latest = (from innerch in g
                                  orderby innerch.UpdatedDate descending,
                                          innerch.SortIndex descending,
                                          innerch.Id descending
                                  select innerch).FirstOrDefault()
                    orderby latest.UpdatedDate descending
                    select new IndexLatestNovel
                    {
                        Novel = (from n in ctx.Novels
                                 where n.Id == g.Key
                                 select n).FirstOrDefault(),
                        LatestChapter = latest,
                        LatestVolume = latest.NovelVolume
                    }).Take(maxItems).ToList();
        }
    }
}